package action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;
import pojo.TbUser;
import service.UserService;
import utils.ResultMap;

import javax.servlet.http.HttpSession;

public class login extends ActionSupport implements ModelDriven {
    private TbUser      tbUser = new TbUser();
    private UserService userService ;
    private ResultMap resultMap = new ResultMap();

    @Override
    public TbUser getModel() {
        return tbUser;
    }

    public TbUser getTbUser() {
        return tbUser;
    }

    public void setTbUser(TbUser tbUser) {
        this.tbUser = tbUser;
    }
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public ResultMap getResultMap() {
        return resultMap;
    }

    public void setResultMap(ResultMap resultMap) {
        this.resultMap = resultMap;
    }

    public String loginTest()
    {
        if(tbUser.getUserName() != null && tbUser.getUserName() != "")
        {
            TbUser login = userService.login(tbUser);
            if(login != null && login.getUserName().equals(tbUser.getUserName()) && login.getUserPassword().equals(tbUser.getUserPassword()))
            {
                HttpSession session = ServletActionContext.getRequest().getSession();
                session.setAttribute("userId" , login.getUserId());
                session.setAttribute("userName" , login.getUserName());
                session.setAttribute("userPassword" , login.getUserPassword());
                return "success";
            }
        }
        return "failed";
    }

    public String loginPanduan()
    {
        if(tbUser.getUserName() != null && tbUser.getUserName() != "")
        {
            TbUser login = userService.login(tbUser);
            if(login != null && login.getUserName().equals(tbUser.getUserName()) && login.getUserPassword().equals(tbUser.getUserPassword()))
            {
               resultMap.code("200").data("success");
                return "success";
            }
        }
        resultMap.code("200").data("failed");
        return "success";
    }


    public String outLogin()
    {
        HttpSession session = ServletActionContext.getRequest().getSession();
        int  id =  session.getAttribute("userId") == null ? -1 : (int)session.getAttribute("userId");
        if(id != -1 )
        {
            resultMap.code("200").data("success");
            session.removeAttribute("userId");
            session.removeAttribute("userName");
            session.removeAttribute("userPassword");
            return "success";
        }
        resultMap.code("201").data("failed");
        return "success";


    }
}
